# Definition for a Node.
class Node(object):
    def __init__(self, val=0, left=None, right=None, next=None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next


class Solution(object):
    def connect(self, root):
        """
        :type root: Node
        :rtype: Node
        """
        if not root:
            return root
        now_layer = [root]
        while now_layer:
            next_layer = []
            for i in range(len(now_layer) - 1):
                now_layer[i].next = now_layer[i + 1]
                if now_layer[i].left:
                    next_layer.append(now_layer[i].left)
                    next_layer.append(now_layer[i].right)
            if now_layer[-1].left:
                next_layer.append(now_layer[-1].left)
                next_layer.append(now_layer[-1].right)
            now_layer = next_layer
        return root
